package com.ysxsoft.wdg.util.camera;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import com.ysxsoft.wdg.constant.MCConfig;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CameraUtils {
    public enum CropType {
        Default, Square, Custom
    }

    private static CameraUtils instance;
    private static final String FILE_CONTENT_FILE_PROVIDER = "com.ysxsoft.wdg.fileprovider";
    private static final String DATE_PATTERN = "yyyyMMddhhmmss";

    private static final int REQUEST_CODE_TAKE_PHOTO = 11111;
    private static final int REQUEST_CODE_SELECT_PICTURE = 11112;
    private static final int REQUEST_CODE_CROP_PICTURE = 11113;

    private static final int DEFAULT_ASPECT_X = 16;
    private static final int DEFAULT_ASPECT_Y = 9;
    private static final int DEFAULT_OUTPUT_X = 320;
    private static final int DEFAULT_OUTPUT_Y = 180;
    private static final int DEFAULT_SQUARE = 200;

    /**
     * 照片图片名
     */
    private String photo_image;
    /**
     * 裁剪图片名
     */
    private String crop_image;
    private String DATE = "";

    private int aspectX = DEFAULT_ASPECT_X;//比例
    private int aspectY = DEFAULT_ASPECT_Y;
    private int outputX = DEFAULT_OUTPUT_X;//输出大小(像素)
    private int outputY = DEFAULT_OUTPUT_Y;
    private int squareSize = DEFAULT_SQUARE;//边长

    private CropType mCropType = CropType.Default;

    private CameraUtils() {

    }


    //重置
    private void setSize() {
        switch (mCropType) {
            case Custom:
                break;
            case Square:
                aspectX = 1;
                aspectY = 1;
                outputX = squareSize;
                outputY = squareSize;
                break;
            case Default://默认
                aspectX = DEFAULT_ASPECT_X;
                aspectY = DEFAULT_ASPECT_Y;
                outputX = DEFAULT_OUTPUT_X;
                outputY = DEFAULT_OUTPUT_Y;
                break;
        }
    }



    /**
     * 启动相机
     */
    @SuppressLint("SimpleDateFormat")
    public void takeCamera(Fragment fragment) {
        DATE = new SimpleDateFormat(DATE_PATTERN).format(new Date());
        photo_image = createImagePath(DATE);
        File file = new File(photo_image);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {//7.0
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//临时授权
            Uri uri = FileProvider.getUriForFile(fragment.getActivity(), FILE_CONTENT_FILE_PROVIDER, file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        }
        fragment.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
    }
    /**
     * 启动相机
     */
    @SuppressLint("SimpleDateFormat")
    public void takeCamera(Activity context) {
        DATE = new SimpleDateFormat(DATE_PATTERN).format(new Date());
        photo_image = createImagePath(DATE);
        File file = new File(photo_image);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {//7.0
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//临时授权
            Uri uri = FileProvider.getUriForFile(context, FILE_CONTENT_FILE_PROVIDER, file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        }
        context.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
    }

    /**
     * 调用系统剪裁功能
     */
    public void cropPicture(Activity activity, String path) {
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        Uri imageUri;
        crop_image = createImagePath("crop_" + DATE);
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            imageUri = FileProvider.getUriForFile(activity, FILE_CONTENT_FILE_PROVIDER, file);
        } else {
            imageUri = Uri.fromFile(file);
        }
        Uri outputUri = Uri.fromFile(new File(crop_image));
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        setSize();
        //设置宽高比例
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        //设置裁剪图片宽高
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        activity.startActivityForResult(intent, REQUEST_CODE_CROP_PICTURE);
        mCropType = CropType.Default;
    }


    /**
     * 调用系统剪裁功能Fragment
     */
    public void cropPicture(Fragment fragment, String path) {
        File file = new File(path);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }

        Uri imageUri;
        crop_image = createImagePath("crop_" + DATE);
        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            imageUri = FileProvider.getUriForFile(fragment.getActivity(), FILE_CONTENT_FILE_PROVIDER, file);
        } else {
            imageUri = Uri.fromFile(file);
        }
        Uri outputUri = Uri.fromFile(new File(crop_image));
        intent.setDataAndType(imageUri, "image/*");
        intent.putExtra("crop", "true");
        setSize();
        //设置宽高比例
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        //设置裁剪图片宽高
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        fragment.startActivityForResult(intent, REQUEST_CODE_CROP_PICTURE);
        mCropType = CropType.Default;
    }

    /**
     * 打开系统相册
     */
    @SuppressLint("SimpleDateFormat")
    public void openAlbum(Activity activity) {
        DATE = new SimpleDateFormat(DATE_PATTERN).format(new Date());
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        activity.startActivityForResult(intent, REQUEST_CODE_SELECT_PICTURE);
    }

    /**
     * 打开系统相册
     */
    @SuppressLint("SimpleDateFormat")
    public void openAlbum(Fragment fragment) {
        DATE = new SimpleDateFormat(DATE_PATTERN).format(new Date());
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
        } else {
            intent = new Intent(Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        fragment.startActivityForResult(intent, REQUEST_CODE_SELECT_PICTURE);
    }


    public void onActivityResult(Activity activity, int requestCode, int resultCode
            , Intent data, OnResultListener listener) {
        if (resultCode == -1)
            switch (requestCode) {
                case REQUEST_CODE_TAKE_PHOTO:
                    if (!TextUtils.isEmpty(photo_image)) {
                        File file = new File(photo_image);
                        if (file.isFile() && listener != null)
                            listener.takePhotoFinish(photo_image);
                    }
                    break;
                case REQUEST_CODE_SELECT_PICTURE:
                    if (data != null) {
                        Uri uri = data.getData();
                        if (uri != null) {
                            String path = CameraHelper.getInstance().getPath(activity, uri);
                            File file = new File(path);
                            if (file.isFile() && listener != null)
                                listener.selectPictureFinish(path);
                        }
                    }
                    break;
                case REQUEST_CODE_CROP_PICTURE:
                    if (!TextUtils.isEmpty(crop_image)) {
                        File file = new File(crop_image);
                        if (file.isFile() && listener != null)
                            listener.cropPictureFinish(crop_image);
                    }
                    break;
            }
    }



    public void onActivityResult(Fragment activity, int requestCode,
                                 int resultCode, Intent data, OnResultListener listener) {
        if (resultCode == -1)
            switch (requestCode) {
                case REQUEST_CODE_TAKE_PHOTO:
                    if (!TextUtils.isEmpty(photo_image)) {
                        File file = new File(photo_image);
                        if (file.isFile() && listener != null)
                            listener.takePhotoFinish(photo_image);
                    }
                    break;
                case REQUEST_CODE_SELECT_PICTURE:
                    if (data != null) {
                        Uri uri = data.getData();
                        if (uri != null) {
                            String path = CameraHelper.getInstance().getPath(activity.getContext(), uri);
                            File file = new File(path);
                            if (file.isFile() && listener != null)
                                listener.selectPictureFinish(path);
                        }
                    }
                    break;
                case REQUEST_CODE_CROP_PICTURE:
                    if (!TextUtils.isEmpty(crop_image)) {
                        File file = new File(crop_image);
                        if (file.isFile() && listener != null)
                            listener.cropPictureFinish(crop_image);
                    }
                    break;
            }
    }

    /**
     * 设置裁剪比例
     */
    public CameraUtils setAspect(int aspectX, int aspectY) {
        if (aspectX < 0 || aspectY < 0)
            throw new IllegalArgumentException("裁剪比例不能小于0");
        this.aspectX = aspectX;
        this.aspectY = aspectY;
        return this;
    }

    /**
     * 设置输出大小，需要和裁剪比例统一
     */
    public CameraUtils setOutput(int outputX, int outputY) {
        if (outputX < 0 || outputY < 0)
            throw new IllegalArgumentException("输出大小不能小于0");
        this.outputX = outputX;
        this.outputY = outputY;
        return this;
    }

    public CameraUtils setCropType(CropType cropType) {
        mCropType = cropType;
        return this;
    }

    public CameraUtils setSquareSize(int squareSize) {
        if (squareSize < 0)
            throw new IllegalArgumentException("裁剪边长不能小于0");
        this.squareSize = squareSize;
        return this;
    }

    public interface OnResultListener {
        /**
         * 拍照回调
         */
        void takePhotoFinish(String path);

        /**
         * 选择图片回调
         */
        void selectPictureFinish(String path);

        /**
         * 裁剪回调
         */
        void cropPictureFinish(String path);
    }

    private String createImagePath(String imageName) {
        String dir = MCConfig.PICTURE_DIR;
        File destDir = new File(dir);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        File file = null;
        if (!TextUtils.isEmpty(imageName)) {
            file = new File(dir, imageName + ".jpg");
        }
        return file.getAbsolutePath();
    }

    public static CameraUtils getInstance() {
        if (instance == null) {
            synchronized (CameraUtils.class) {
                if (instance == null) {
                    instance = new CameraUtils();
                }
            }
        }
        return instance;
    }
}
